package org.benjamin.lending.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


public class CustomUserDetailsService implements UserDetailsService{
	
	private final Logger logger = LogManager.getLogger();
	
	@Autowired
	private MemberService memberService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if(StringUtils.isBlank(username)) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		logger.info("检查MemberService对象:{}",this.memberService);
		MemberInfo memberInfo = this.memberService.userLogin(username);
		if(memberInfo != null) {
			logger.info("成功查询到用户信息:{}",memberInfo.getUsername());
			List<GrantedAuthority> authorities = new ArrayList<>();
			return new User(username, memberInfo.getPassword(), authorities);
		}
		logger.info("当前用户名不存在");
		throw new UsernameNotFoundException("当前用户名"+username+" 不存在.");
	}

}
